package calculate24.play.SelfCalculate.CardsHistory;

class VersionList<T> {
    private int index = -1; //现在所处版本的下标
    private int size; //现有版本总数
    private int capacity; //列表容量
    private Object[] versions;

    VersionList(int capacity) {
        this.capacity = capacity;
        versions = new Object[capacity];
    }

    T getCurrentVersion() {
        if (size > 0) {
            return (T) versions[index];
        }
        return null;
    }

    boolean canRollBack() {
        return index > 0;
    }

    boolean canRollForward() {
        return (index + 1) < size;
    }

    boolean rollBack() {
        if (canRollBack()) {
            index--;
            return true;
        }
        return false;
    }

    boolean rollForward() {
        if (canRollForward()) {
            index++;
            return true;
        }
        return false;
    }

    //在当前版本之后附加一个新的版本，放弃后面原来的版本
    boolean fork(T newVersion) {
        if (canRollForward()) {
            versions[index + 1] = newVersion;
            size = index + 2;
            return true;
        }
        return false;
    }

    //在版本列表末尾附加一个新的版本
    boolean append(T newVersion) {
        if (size < capacity) {
            versions[size] = newVersion;
            size++;
            return true;
        }
        return false;
    }
}
